import axios from "axios";
// import store from "../store";
// import Cookies from 'js-cookie'

import { BaseUrl } from "./config";
import { Message } from "element-ui";

const instance = axios.create({
  baseURL: BaseUrl,
  timeout: 30000
});

instance.interceptors.request.use(
  (config) => {
    // let token = store.getters.userToken;
    let token = sessionStorage.getItem('token')
    if (token) {
      config.headers["Authorization"] = token;
    }
    // TODO
    // store.commit("SHOW_LOADING");
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (response) => {
    let res = response.data;
    switch (res.status) {
      case 0:
      case 200:
        break;
      case -1:
        Message.error(res.msg);
        break;
    }
    // TODO
    // store.commit("HIDE_LOADING");
    return response;
  },
  (error) => {
    // if (!window.localStorage.getItem("loginUserBaseInfo")) {
    //   // 若是接口访问的时候没有发现有鉴权的基础信息,直接返回登录页
    //   router.push({
    //     path: "/login"
    //   });
    // }
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = "请求错误";
          break;
        case 401:
          error.message = "未授权，请登录";
          break;
        case 403:
          error.message = "拒绝访问";
          break;
        case 404:
          error.message = "资源不存在";
          break;
        case 500:
          error.message = "服务器内部出错";
          break;
        case 502:
          error.message = "网关错误";
          break;
        default:
          error.message = "请求失败";
      }
    }
    Message.error(error.message);
    // store.commit("HIDE_LOADING");
    return Promise.reject(error);
  }
);

const apiMethod = ["get", "post", "put", "delete"];
const api = {};

apiMethod.forEach((method) => {
  api[method] = (url, params, config) => {
    return new Promise((resolve, reject) => {
      instance[method](url, params, config)
        .then((res) => {
          // if (res.status !== 200) {
          //   // 此处可以统一处理请求返回值
          //   Message.error(res.data.message)
          // } else {
          //   resolve(res)
          // }
          resolve(res);
        })
        .catch((err) => {
          console.log(err); // 开发环境下开启查看错误信息
          reject(err);
          Message.error("请求服务器失败，请稍后重试");
        });
    });
  };
});

export default api;
